package com.jammingpro.blog_system.controller;

import com.jammingpro.blog_system.constant.Constant;
import com.jammingpro.blog_system.model.Result;
import com.jammingpro.blog_system.model.UserInfo;
import com.jammingpro.blog_system.service.UserService;
import com.jammingpro.blog_system.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.TileObserver;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/redirect")
    public Boolean redirect() {
        return true;
    }

    /**
     * 登录验证接口
     * @param userInfo 用户登录信息
     * @return 统一返回结果-是否登录成功
     */
    @RequestMapping("/login")
    public Result login(UserInfo userInfo) {
        // 用户名与密码参数有效性校验
        if(!StringUtils.hasLength(userInfo.getUserName())) {
            return Result.fail("用户名为空");
        }
        if(!StringUtils.hasLength(userInfo.getPassword())) {
            return Result.fail("密码为空");
        }

        // 校验用户名与密码是否正确
        UserInfo ret = userService.getUserInfoByUserName(userInfo);

        // 返回错误结果
        if(ret == null || !ret.getPassword().equals(userInfo.getPassword())) {
            return Result.fail("用户名或密码错误");
        }

        // JWT令牌构造
        Map<String, Object> map = new HashMap<>();
        map.put(Constant.TOKEN_USER_ID, ret.getId());
        String token = JwtUtils.genToken(map);

        // 返回正确结果（包含令牌）
        return Result.success(token);
    }

    /**
     * 获取文章作者信息
     * @param id 文章id
     * @return 文章作者信息-统一结果返回
     */
    @RequestMapping("/getAuthorInfo")
    public Result getAuthorInfo(Integer id) {
        UserInfo userInfo = userService.getAuthorInfo(id);
        if(userInfo == null) {
            Result.fail("信息错误");
        }
        return Result.success(userInfo);
    }

    /**
     * 获取登录用户信息
     * @param request Http请求
     * @return 统一结果返回
     */
    @RequestMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        // 解析令牌中的用户id
        String token = request.getHeader(Constant.REQUEST_USER_TOKEN);
        Integer id = JwtUtils.getIdByToken(token);
        if(id == null) {
            log.info("token {} 's id is null", token);
            return Result.fail("信息错误");
        }

        // 查询用户信息
        UserInfo userInfo = userService.getUserInfoById(id);
        if(userInfo == null) {
            log.info("userInfo is null, id is {}", id);
            return Result.fail("信息错误");
        }
        return Result.success(userInfo);
    }
}
